package com.chcit.mobile.mvp.model;

import android.app.Application;

import com.alibaba.fastjson.JSONObject;
import com.chcit.mobile.mvp.model.api.cache.CommonCache;
import com.chcit.mobile.mvp.model.api.service.CommonService;
import com.chcit.mobile.mvp.model.api.service.UserService;
import com.chcit.mobile.mvp.model.entity.BaseData;
import com.chcit.mobile.mvp.model.entity.GoodsAllocation;
import com.chcit.mobile.mvp.model.entity.ResultBean;
import com.chcit.mobile.mvp.model.entity.Statu;
import com.google.gson.Gson;
import com.jess.arms.integration.IRepositoryManager;
import com.jess.arms.mvp.BaseModel;

import com.jess.arms.di.scope.FragmentScope;

import javax.inject.Inject;

import com.chcit.mobile.mvp.contract.InventoryDetailContract;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;
import io.rx_cache2.DynamicKey;
import io.rx_cache2.EvictProvider;


@FragmentScope
public class InventoryDetailModel extends BaseModel implements InventoryDetailContract.Model {
    @Inject
    Gson mGson;
    @Inject
    Application mApplication;

    @Inject
    public InventoryDetailModel(IRepositoryManager repositoryManager) {
        super(repositoryManager);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mGson = null;
        this.mApplication = null;
    }

    @Override
    public Observable<List<GoodsAllocation>> getLocators(int id, boolean update) {
        return Observable.just(mRepositoryManager
                .obtainRetrofitService(CommonService.class)
                .getLocators(id).map(new Function<BaseData<GoodsAllocation>, List<GoodsAllocation>>() {
                    @Override
                    public List<GoodsAllocation> apply(BaseData<GoodsAllocation> json) throws Exception {
                        if(json.getTotal()>0){
                            return json.getRows();
                        }else{
                            throw new Exception("没有查询到货位！");
                        }
                    }
                }))
                .flatMap((Function<Observable<List<GoodsAllocation>>, ObservableSource<List<GoodsAllocation>>>) listObservable
                        ->
                        mRepositoryManager.obtainCacheService(CommonCache.class)
                                .getLocators(listObservable,new DynamicKey(id),new EvictProvider(update)));

    }

    @Override
    public Observable<ResultBean> moven(JSONObject json) {
        return  mRepositoryManager
                .obtainRetrofitService(UserService.class)
                .moven(json);
    }

}